#!/bin/bash
# Simple PCAP to JSON Converter (Shell Script Alternative)
# This demonstrates that shell scripts can also convert PCAP to JSON format

set -e

# Usage function
usage() {
    echo "Usage: $0 <input.pcap> [output.json]"
    echo "Example: $0 input.pcap output.json"
    echo "Example: $0 input.pcap (uses default output name)"
    exit 1
}

# Check arguments
if [[ $# -lt 1 ]]; then
    usage
fi

INPUT_FILE="$1"
OUTPUT_FILE="${2:-${INPUT_FILE%.pcap}.json}"

# Check if input file exists
if [[ ! -f "$INPUT_FILE" ]]; then
    echo "Error: Input file '$INPUT_FILE' not found"
    exit 1
fi

echo "Converting $INPUT_FILE to $OUTPUT_FILE..."

# Create JSON structure
cat > "$OUTPUT_FILE" << EOF
{
  "metadata": {
    "input_file": "$INPUT_FILE",
    "output_file": "$OUTPUT_FILE",
    "conversion_time": "$(date -Iseconds)",
    "conversion_method": "shell_script"
  },
  "statistics": {
    "total_packets": 0,
    "protocols": {},
    "source_ips": {},
    "dest_ips": {},
    "ports": {}
  },
  "packets": [
EOF

# Process packets using tcpdump and awk
PACKET_COUNT=0
FIRST_PACKET=true

# Use tcpdump to get packet information and process with awk
tcpdump -r "$INPUT_FILE" -n 2>/dev/null | while IFS= read -r line; do
    if [[ -n "$line" ]]; then
        # Parse the line using awk-like logic in bash
        # Format: timestamp interface direction IP src.port > dst.port: details
        
        # Extract timestamp
        timestamp=$(echo "$line" | grep -o '^[0-9:.]*')
        
        # Extract interface
        interface=$(echo "$line" | grep -o 'ens[0-9]*\|eth[0-9]*\|lo\|any' | head -1)
        
        # Extract direction
        direction=$(echo "$line" | grep -o 'In\|Out')
        
        # Extract IP addresses and ports
        ip_port_pattern='([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\.([0-9]+)'
        if [[ "$line" =~ $ip_port_pattern ]]; then
            src_ip="${BASH_REMATCH[1]}"
            src_port="${BASH_REMATCH[2]}"
        fi
        
        # Extract destination IP and port
        if [[ "$line" =~ $ip_port_pattern.*$ip_port_pattern ]]; then
            dst_ip="${BASH_REMATCH[3]}"
            dst_port="${BASH_REMATCH[4]}"
        fi
        
        # Extract details (everything after the colon)
        details=$(echo "$line" | sed 's/.*: //')
        
        # Determine protocol
        protocol="Unknown"
        if echo "$details" | grep -q -i "sctp"; then
            protocol="SCTP"
        elif echo "$details" | grep -q -i "tcp"; then
            protocol="TCP"
        elif echo "$details" | grep -q -i "udp"; then
            protocol="UDP"
        elif echo "$details" | grep -q -i "icmp"; then
            protocol="ICMP"
        fi
        
        # Extract packet size if available
        size=$(echo "$details" | grep -o 'length [0-9]*' | grep -o '[0-9]*')
        if [[ -z "$size" ]]; then
            size="null"
        fi
        
        # Add comma if not first packet
        if [[ "$FIRST_PACKET" == "true" ]]; then
            FIRST_PACKET=false
        else
            echo "," >> "$OUTPUT_FILE"
        fi
        
        # Write packet JSON
        cat >> "$OUTPUT_FILE" << EOF
    {
      "timestamp": "$timestamp",
      "interface": "$interface",
      "direction": "$direction",
      "source": {
        "ip": "$src_ip",
        "port": $src_port
      },
      "destination": {
        "ip": "$dst_ip",
        "port": $dst_port
      },
      "details": "$details",
      "protocol": "$protocol",
      "size": $size
    }
EOF
        
        PACKET_COUNT=$((PACKET_COUNT + 1))
        
        # Update progress every 100 packets
        if [[ $((PACKET_COUNT % 100)) -eq 0 ]]; then
            echo "Processed $PACKET_COUNT packets..." >&2
        fi
    fi
done

# Close JSON structure
cat >> "$OUTPUT_FILE" << EOF
  ]
}
EOF

# Update packet count in the JSON file
sed -i "s/\"total_packets\": 0/\"total_packets\": $PACKET_COUNT/" "$OUTPUT_FILE"

echo "Conversion completed!"
echo "Total packets processed: $PACKET_COUNT"
echo "Output file: $OUTPUT_FILE"

# Generate simple statistics
echo
echo "=== Quick Statistics ==="
echo "Total packets: $PACKET_COUNT"

# Count protocols
echo "Protocols found:"
tcpdump -r "$INPUT_FILE" -n 2>/dev/null | grep -o -i "sctp\|tcp\|udp\|icmp" | sort | uniq -c | while read count protocol; do
    echo "  $protocol: $count"
done

# Show top source IPs
echo "Top source IPs:"
tcpdump -r "$INPUT_FILE" -n 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' | sort | uniq -c | sort -nr | head -5 | while read count ip; do
    echo "  $ip: $count"
done

echo
echo "For detailed analysis, use the Python version:"
echo "  python3 pcap-to-json.py $INPUT_FILE" 